package cn.donting.web.desktop.core.app;

import cn.donting.web.desktop.core.dao.UserRepository;
import cn.donting.web.desktop.core.entity.User;
import cn.donting.web.desktop.core.listener.AppListener;
import cn.hutool.core.io.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Map;

/**
 * 用户管理器
 *
 * @author donting
 * 2021-06-12 下午12:25
 */
@Service
@Slf4j
public class UserManager implements ApplicationRunner {

    public static final String USER_PATH = AppManager.SYS_PATH + File.separator + "users";
    public static final String SYS_USEr_NAME = "admin";

    @Autowired
    UserRepository userRepository;

    @Autowired
    ApplicationContext applicationContext;


    public User creatUser(String name, String password) {
        User user = new User();
        user.setName(name);
        user.setPassword(password);
        user = userRepository.save(user);
        creatUserSpace(user);
        return user;
    }

    private void creatUserSpace(User user) {
        String path = USER_PATH + File.separator + user.getName();
        File desktop = new File(path + File.separator + "desktop");
        desktop.mkdirs();
    }

    public User deleteUser(String name) {
        User user = userRepository.findByName(name);
        if (user == null) {
            log.warn("user[{}]不存在", name);
            return null;
        }
        String path = USER_PATH + File.separator + user.getName();
        File file = new File(path);
        if (!FileUtil.del(file)) {
            log.error(file.getPath() + "删除失败！！");
        }
        userRepository.deleteById(user.getId());
        return user;
    }

    /**
     * 第一次运行检查是否创建 admin，否创建默认admin
     *
     * @param args
     * @throws Exception
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        User admin = userRepository.findByName("admin");
        if (admin != null) {
            return;
        }
        //创建sys用户
        creatUser(SYS_USEr_NAME, SYS_USEr_NAME);
        //触发AppListener#inin();
        Map<String, AppListener> beansOfType = applicationContext.getBeansOfType(AppListener.class);
        try {
            for (Map.Entry<String, AppListener> appListenerEntry : beansOfType.entrySet()) {
                appListenerEntry.getValue().init();
            }
        } catch (Exception ex) {
            log.error(" init() fail ");
            log.error(ex.getMessage(), ex);
            log.error("初始化失败");
            SpringApplication.exit(this.applicationContext);
            FileUtil.del(AppManager.SYS_PATH);
        }
    }


}
